package cn.digiwin.wx.gzh.common;

import cn.digiwin.wx.model.TokenModel;
import cn.digiwin.wx.utils.HttpUtil;
import cn.e4j.config.WxGzhProperties;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.util.SpringContextHolder;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;

/**
 * 用于服务号
 * Created by wenchuan.li on 2018/4/9.
 */
public class WeixinGzhComm {

    protected static Logger logger = LoggerFactory.getLogger(WeixinGzhComm.class);

    public final static String METHOD_GET = "GET";
    public final static String METHOD_POST = "POST";
    private final static String QIYE_URL = "https://api.weixin.qq.com/cgi-bin";
    public final static String ACCOUNT_HEAD = "GZH_";

    private static TokenModel modelGzh = new TokenModel();

    /**
     * 多媒体文件下载
     */
    private final static String QY_MEDIA_URL = QIYE_URL + "/media";

    private final static WxGzhProperties wxGzhProperties= SpringContextHolder.getBean(WxGzhProperties.class);

    /**
     * 获取多媒体文件下载完整路径
     *
     * @param media_id
     * @return
     */
//    public static String getWxMediaURL(String media_id) {
//        return QY_MEDIA_URL + "/get?access_token=" + TokenUtil.getTokenGzh() + "&media_id=" + media_id;
//    }

    /**
     * 获取 基础access_token
     *
     * @return
     */
    public static synchronized String getAccessToken() {
        //没有初始化直接获取。
        if (!modelGzh.isInit()) {
            return getTokenGzh();
        } else {
            //如果token要过期则重新获取。
            if (modelGzh.isExpire()) {
                return getTokenGzh();
            } else {
                //从缓存中获取。
                return modelGzh.getToken();
            }
        }

    }

    private static String getTokenGzh() {

        String rtn = "";
        try {
            rtn = HttpUtil.sendHttpsRequest(QIYE_URL
                    + "/token?grant_type=client_credential&appid="
                    + wxGzhProperties.getAppid()
                    + "&secret=" + wxGzhProperties.getSecret(), "", WeixinGzhComm.METHOD_GET);
        } catch (KeyManagementException | NoSuchAlgorithmException
                | NoSuchProviderException | IOException e) {
            e.printStackTrace();
        }

//        Dto dto = AppJson.fromJson(rtn, HashDto.class);
        JSONObject dto = JSONObject.parseObject(rtn);
        if (rtn.indexOf("errcode") == -1) {
            String token = dto.getString("access_token");
            int expireIn = dto.getInteger("expires_in");
            modelGzh.setToken(token, expireIn);
            return token;
        } else {//获取失败
            logger.error(rtn);
            return "-1";
        }
    }

    /**
     * 用于进行网页授权验证的接口URL，通过这个才可以得到opendID等字段信息
     * <p>
     * 得到的内容：access_token expires_in  refresh_token openid scope
     */
    public static String oauth2GetOpenid(String code) {
        Dto result = Dtos.newDto();
        String json = "";
        try {
            json = HttpUtil.sendHttpsRequest("https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + wxGzhProperties.getAppid()
                    + "&secret="
                    + wxGzhProperties.getSecret()
                    + "&code=" + code + "&grant_type=authorization_code", "", WeixinGzhComm.METHOD_GET);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;
    }

    /**
     * 获取微信验证地址。
     *
     * @param redirectUrl
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getWxAuthorize(String redirectUrl) throws UnsupportedEncodingException {
        String corpId = wxGzhProperties.getAppid();
        String redirect = URLEncoder.encode(redirectUrl, "utf-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + corpId + "&redirect_uri=" + redirect + "&response_type=code&scope=snsapi_base&state=digiwin#wechat_redirect";
        return url;
    }

    /**
     * 根据code获取用户信息
     *
     */
    public static String getWxUserInfo(String code) {
        Dto result = Dtos.newDto();
        String json = "";
        try {
            String openidStr = oauth2GetOpenid(code);
            JSONObject openidDto = JSONObject.parseObject(openidStr);
            json = HttpUtil.sendHttpsRequest("https://api.weixin.qq.com/cgi-bin/user/info?access_token="
                    + getAccessToken()
                    + "&openid="
                    + openidDto.getString("openid"), "", WeixinGzhComm.METHOD_GET);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;
    }

    /**
     * 获取微信 jsapi_ticket url。
     *
     * @return
     */
    public static String getWxJsapiTicketUrl() {
        String accessToken = getAccessToken();
        logger.debug("...accessToken: " + "accessToken: " + accessToken);
        return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
    }

    /**
     * 根据userid 获取成员信息
     *
     * @param userid
     * @return
     */
    public static String getWxStaff(String userid) {
        String accessToken = getAccessToken();
        String url = QIYE_URL + "/user/get?access_token=" + accessToken + "&userid=" + userid;
        return url;
    }

    /**
     * 发送消息
     *
     * @return
     */
    public static String sendMsg() {
        String accessToken = getAccessToken();
        String url = QIYE_URL + "/message/send?access_token=" + accessToken;
        return url;
    }

    /**
     * 发送消息
     *
     * @return
     */
    public static void sendMsg(List<String> ids, String msg) {
        try {
            for(int i=0, j=ids.size();i<j;i++){

                HttpUtil.sendHttpsRequest("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + getAccessToken(),
                        String.format("{\"touser\" : \"%s\",\"msgtype\" : \"text\",\"text\" : %s}",
                                ids.get(i),
                                msg),
                        "POST");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
